class Cart{
    constructor(){
        this.url = "http://localhost:3000/api";
        this.tbody = document.querySelector("tbody");
        this.getLocal()
        this.load()
        this.addEvent()
    }
    addEvent(eve){
        const that = this
        this.tbody.addEventListener("input",function(eve){
            const e = eve || window.event
            const target = e.target || e.srcElement
            if(target.className === "setNum"){
                that.id = target.parentNode.parentNode.getAttribute("index")  //tr的index
                that.num = target.value-0
                that.setLocal(function(i){
                    that.goods[i].num = that.num
                })
            }
        })
        this.tbody.addEventListener("click",function(eve){
            const e = eve || window.event
            const target = e.target ||e.srcElement
            if(target.className === "del"){
                that.id = target.parentNode.parentNode.getAttribute("index")  //tr的index
                target.parentNode.remove()
                that.setLocal(function(i){
                    that.goods.splice(i,1)
                })
            }
        })
    }
    load(){
        ajax({
            url:this.url,
            data:{
                type:"getGoods"
            },
            success:res=>{
                this.res=JSON.parse(res).msg
                this.render()
            }
        })
    }
    setLocal(cb){
        let i = 0
        this.goods.some((val,idx)=>{
            i=idx
            return val.id===this.id
        })
        cb(i)
        localStorage.setItem("goods",JSON.stringify(this.goods))
    }
    getLocal(){
        this.goods = localStorage.getItem("goods") ? JSON.parse(localStorage.getItem("goods")) : []
    }
    render(){
        let str = ""
        this.res.forEach(val1=>{
            this.goods.forEach(val2=>{
                if(val1.proId===val2.id){
                    str +=  `<tr index="${val2.id}">
                                <td><input type="checkbox"></td>
                                <td><img src="${val1.img}" alt=""></td>
                                <td>${val1.proName}</td>
                                <td><input type="number" class="setNum" value="${val2.num}"></td>
                                <td>${val1.price}</td>
                                <td>${val2.num * val1.price}</td>
                                <td class="del">删除</td>
                            </tr>`
                }
            })
        })
        this.tbody.innerHTML = str;
    }
}
new Cart()